<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
  * Clase para inicial por defecto.
  *
  * @autor  Andres Hocevar <aahahocevar@gmail.com>
  * @package controllers
  */
class Inicio extends CI_Controller {
	var $adjuntos='';

	public function index(){
		$c1=$c2=0;
		$dbprefix=$this->db->dbprefix;

		if ($this->db->table_exists("${dbprefix}curso")){
			$this->db->from('curso');
			$c1 = $this->db->count_all_results();
		}

		if ($this->db->table_exists("${dbprefix}curso")){
			$this->db->from('integrantes');
			$this->db->where('tipo','P');
			$c2 = $this->db->count_all_results();
		}

		if($c1*$c2 == 0){
			redirect('instalador');
		}

		$this->login();
	}

/**
  * Método que muestra el formulario para autentificar un usuario.
  *
  * @return  void
  */
	public function login(){
		$this->load->helper('form');
		$this->load->library('rapyd');

		$ut= new rpd_auth_library();

		$usr = $this->input->post('usr');
		$pwd = md5($this->input->post('pwd'));
		$error='';

		if($usr!==false){
			$rt=$ut->login($usr,$pwd);
			if($rt){
				$rol=$ut->role();
				$this->db->from('integrantes AS a');
				$this->db->join('integrantes AS b','a.id_compania=b.id_compania');
				$this->db->where('a.usuario',$usr);
				$this->db->where('a.id_compania IS NOT NULL');
				$this->db->where('a.id_compania <>','');
				$cant = $this->db->count_all_results();
				if($cant==1 && $rol!=2){
					$this->db->where('usuario', $usr);
					$this->db->update('integrantes', array('cargo' => 'G'));
					$ut->login($usr,$pwd);
				}

				if($rol==1){
					redirect('dashboard');
				}else{
					redirect('dashboard/gcompalu');
				}
			}else{
				$ut->logout();
				$error='Usuario o clave no v&aacute;lida';
			}
		}

		$conten=array();
		$conten['error']=$error;

		$obj = $this->load->view('view_login',$conten ,true);
		$data['content']    = $obj;
		$data['header']     = 'Gesti&oacute;n RAIS';
		$data['title']      = 'Gesti&oacute;n RAIS';
		$data['footer']     = '';

		$data['onLoadScript']='$.extend(  $.mobile , {
			ajaxFormsEnabled: false
		});';

		$this->load->view('view_ven', $data);
	}

/**
  * Método para el cierre de sessión de usuario.
  *
  * @return  void
  */
	public function logout(){
		$this->load->library('rapyd');

		$ut= new rpd_auth_library();
		$ut->logout();
		$this->login();
	}

	public function correos(){
		$envio=$this->input->post('btn_envio');
		if($envio!==false){
			$to      = $this->input->post('mensaje');
			$subject = 'Proyecto GeRais';
			$body    = $this->input->post('texto');
			$this->adjuntos='';
			$rt=$this->_mail($to,$subject,$body);
			//$rt=true;
			if($rt){
				$data['msj'] = 'Mensaje enviado';
			}else{
				$data['msj'] = 'Error enviando mensaje';
			}

		}else{
			$data['msj'] = '';
		}

		$this->load->helper('form');
		$sel=array('TRIM(a.correo) AS correo','CONCAT_WS(\' \',a.nombre,a.apellido) AS nombre');
		$this->db->select($sel);
		$this->db->from('integrantes AS a');
		$query = $this->db->get();
		$correos=array();
		foreach ($query->result() as $row){
			$correos[$row->correo]=$row->nombre;
		}

		$data['correos']   = $correos;
		$data['titulo']    = '<h1>Correos</h1>';
		$this->load->view('view_correos',$data);
	}

/**
  * Método para proporcionar información de la instancia al panal
  *
  * @return  void
  */
	function info(){
		$dbprefix=$this->db->dbprefix;

		if (!$this->db->table_exists("${dbprefix}curso")){
			header('Content-Type: text/html; charset=utf-8');
			echo "No instalado\n";
			echo "\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo "0\n";
			echo '0';
			return;
		}
		
		$sel=array('nombre','profesor');
		$this->db->select($sel);
		$this->db->from('curso AS a');
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$nombre = $row->nombre;
			$profe  = $row->profesor;
		}else{
			$nombre = 'No hay información del curso';
			$profe  = 'No hay profesor en este curso';
		}

		$this->db->select_sum('reasignado','reasignado');
		$this->db->from('compromisos');
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$reasignado = $row->reasignado;
		}else{
			$reasignado = 0;
		}


		$this->db->select_sum('reasignado','reasignado');
		$this->db->from('compromisos');
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$reasignado = $row->reasignado;
		}else{
			$reasignado = 0;
		}

		$this->db->select(array('COUNT(*) AS cana'));
		$this->db->from('compromisos');
		$this->db->where('ejecucion <',100);
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$culmi = $row->cana;
		}else{
			$culmi = 0;
		}

		$this->db->select(array('COUNT(*) AS cana'));
		$this->db->from('subcompromisos');
		$this->db->where('ejecucion <',100);
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$sculmi = $row->cana;
		}else{
			$sculmi = 0;
		}

		$this->db->select(array('COUNT(*) AS cana'));
		$this->db->from('subcompromisos');
		$this->db->where('registro','P');
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$psub = $row->cana;
		}else{
			$psub = 0;
		}

		$integrantes   = $this->db->count_all_results('integrantes');
		$evaluaciones  = $this->db->count_all_results('aucoevaluacion');
		$evaluados     = $this->db->count_all_results('aucoevaluacion_it');
		$companias     = $this->db->count_all_results('compania');
		$compromisos   = $this->db->count_all_results('compromisos');
		$productos     = $this->db->count_all_results('producto');
		$subcompromisos= $this->db->count_all_results('subcompromisos');
		$isas          = $this->db->count_all_results('subcomproresol');
		$penaliza      = $this->db->count_all_results('penalizaciones');

		header('Content-Type: text/html; charset=utf-8');
		echo str_replace("\n",'',$nombre)."\n";
		echo str_replace("\n",'',$profe)."\n";
		echo $integrantes."\n";
        echo $evaluaciones."\n";
        echo $companias."\n";
        echo $compromisos."\n";
        echo $productos."\n";
        echo $subcompromisos."\n";
		echo $isas."\n";
		echo $penaliza."\n";
		echo $reasignado."\n";
		echo $culmi."\n";
		echo $sculmi."\n";
		echo $evaluados."\n";
		echo $psub;
	}

/**
  * Método para enviar correo electrónicos.
  *
  * @return  boolean
  */
	function _mail($to,$subject,$body){
		$this->config->load('notifica');
		if(!@include_once 'Mail.php'){
			$this->error='Problemas al cargar la clase Mail, probablemente sea necesario instalarla desde PEAR, comuniquese con soporte t&eacute;cnico';
			return false;
		}
		if(!@include_once 'Mail/mime.php'){
			$this->error='Problemas al cargar la clase Mail_mime, probablemente sea necesario instalarla desde PEAR, comuniquese con soporte t&eacute;cnico';
			return false;
		}

		$from = $this->config->item('mail_smtp_from');
		$host = $this->config->item('mail_smtp_host');
		$port = $this->config->item('mail_smtp_port');
		$user = $this->config->item('mail_smtp_usr');
		$pass = $this->config->item('mail_smtp_pwd');

		if(is_array($this->adjuntos)){
			$message = new Mail_mime();
			$message->setTXTBody($body);

			foreach($this->adjuntos AS $adj){
				$message->addAttachment($adj);
			}

			$body = $message->get();
			$extraheaders =  array (
				'From'    => $from,
				'To'      => $to,
				'Subject' => $subject
			);
			$headers = $message->headers($extraheaders);

		}else{
			$headers = array (
				'From'    => $from,
				'To'      => $to,
				'Subject' => $subject
			);
			$body.="\n\nEsta es una cuenta de correo no monitoreada. Por favor no responda o reenvíe mensajes a esta cuenta.";
		}

		$parr=array (
			'host'     => $host,
			'port'     => $port,
			'auth'     => true,
			'username' => $user,
			'password' => $pass
		);

		$smtp = Mail::factory('smtp',$parr);
		$mail = $smtp->send($to, $headers, $body);
		if (PEAR::isError($mail)) {
			$this->error=$mail->getMessage();
			return false;
		} else {
			return true;
		}
	}
}
